<script setup lang="ts">
import { reactive, ref } from 'vue'
import { Effect } from 'element-plus'
import type { ElTable } from 'element-plus'
import ListBtnGroup from '@/components/list-btn-group/index.vue'
import { DictionaryType, TableKeyListItemType, BatchBtnItemType } from '@/common/types/conf'
import { formatDate } from '@/common/utils/utils'
import { useCurrentInstance } from '@/common/utils/methods'
const { $message } = useCurrentInstance();

interface Props {
  tableKeyList: TableKeyListItemType[]  // 列表 key name
  list: object[]                        // 列表数据
  dictionary?: DictionaryType            // 列表字段对应字典
  fixed?: boolean | string              // 操作列固定位置
  hasHandle?: boolean                    // 是否显示 操作列
  showSelectNum?: boolean
  batchBtnList?: Array<BatchBtnItemType>
  totalNum?: number
}

// 参考文档：https://v3.cn.vuejs.org/api/sfc-script-setup.html#%E4%BB%85%E9%99%90-typescript-%E7%9A%84%E5%8A%9F%E8%83%BD
const props = withDefaults(defineProps<Props>(), {
  totalNum: 0,
  hasHandle: false,
  showSelectNum: false
})

const emit = defineEmits<{
  (e: 'batchConfirm', val: Array<unknown>, status: number): void
}>()

const data = reactive({
  selectable: function(row: {isEnabled: number; [propName: string]: any}){
    return row.isEnabled === 0;
  },
  showSelection: false,
  tableSelect: [] as Array<unknown>
})

const setSelectableFunc = (enabledKey: string, enableValue: number | string) => {
  data.selectable = function(row: object){
    return row[enabledKey] === enableValue
  };
  data.showSelection = true;
}

const listBtnGroup = ref();
const handleSelectionChange = (val: Array<unknown>) => {
  data.tableSelect = val;
  listBtnGroup.value?.setSelectData(val)
}

const batchConfirm = (status: number) => {
  emit('batchConfirm', data.tableSelect, status)
}

const tableRef = ref<InstanceType<typeof ElTable>>()
const batchReset = () => {
  data.showSelection = false;
  data.tableSelect = [];
  tableRef.value!.clearSelection();
}

// 数据默认格式化（默认使用字典格式数据，字典中不存在的使用原始数据）
const formatDefault = (data: any, key: string): string | number | undefined => {
  const dictionary = props.dictionary;
  if (dictionary && dictionary[key]) {
    const res = dictionary[key].filter((item) => item.value == data[key])
    return res[0].label;
  } else {
    return data[key];
  }
}

</script>

<template>
  <div>
    <!-- 列表操作：批处理等按钮 -->
    <ListBtnGroup 
      v-if="batchBtnList"
      ref="listBtnGroup" 
      :totalNum="totalNum" 
      :batchBtnList="batchBtnList"
      @selection="setSelectableFunc"
      @reset="batchReset" 
      @batchConfirm="batchConfirm">
      <slot name="rightBtn"></slot>
    </ListBtnGroup>
    <el-table 
      ref="tableRef" 
      :data="list" 
      :border="true" 
      style="width:100%" 
      @selection-change="handleSelectionChange">
      <el-table-column 
        v-if="data.showSelection"
        type="selection" 
        width="55" 
        :selectable="data.selectable"
      ></el-table-column>
      <el-table-column
        v-for="keyItem in tableKeyList"
        :key="keyItem.key"
        :label="keyItem.label"
        :min-width="keyItem.width || 180"
      >
        <template #default="{ row, $index }">
          <slot :name="keyItem.key" v-bind="{  row, $index  }">
            <span v-if="keyItem.type == 'datetime'">{{ formatDate(row[keyItem.key]) }}</span>
            <!-- 超出隐藏 -->
            <span v-else-if="keyItem.type === 'ellipsis'">
              <template v-if="row[keyItem.key] && row[keyItem.key].length > 28">
                <el-tooltip
                  popper-class="_tooltip"
                  :effect="Effect.LIGHT"
                  :content="row[keyItem.key]"
                  placement="top-start"
                >
                  <span>{{ row[keyItem.key].slice(0, 18) }}...</span>
                </el-tooltip>
              </template>
              <template v-else>{{ row[keyItem.key] }}</template>
            </span>
            <span v-else>{{ formatDefault(row, keyItem.key) }}</span>
          </slot>
        </template>
      </el-table-column>
      <el-table-column :fixed="fixed" label="操作" :width="360" v-if="hasHandle">
        <template #default="scope">
          <slot name="handle" v-bind="scope"></slot>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped></style>